package com.xue.web.dao;

import com.xue.web.entity.LeaveMessage;
import com.xue.web.mapper.LeaveMessageMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class LeaveMessageDao {
    public List<LeaveMessage>  selectMessage() {
        InputStream is;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(is);
        SqlSession sqlSession = factory.openSession();
        LeaveMessageMapper mapper = sqlSession.getMapper(LeaveMessageMapper.class);
        List<LeaveMessage> leaveMessage = mapper.selectMessage();


        try {
            is.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return leaveMessage;
    }

    public boolean insertMessage(String user,String message){
        InputStream is;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(is);
        SqlSession sqlSession = factory.openSession(true);
        LeaveMessageMapper mapper = sqlSession.getMapper(LeaveMessageMapper.class);
        LeaveMessage leaveMessage =new LeaveMessage();
        leaveMessage.setUser_name(user);
        leaveMessage.setMessage(message);
        int i = mapper.insertMessage(leaveMessage);

        try {
            is.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return i != 0;
    }
}
